const {Ask, House, User, Area} = require('../db/model/index')
const {Op} = require('sequelize')

const getAskList = async ({askId, ownerId, status, createTime, pageIndex, pageSize}) => {
  const where = {}

  const whereUser = {}

  if (askId !== undefined) {
    where.askId = askId
  }

  if (ownerId !== undefined) {
    whereUser.uid = ownerId
  }

  if (status !== undefined) {
    where.status = status
  }

  if (createTime.length) {
    where[`created_at`] = {
      [Op.gte]: createTime[0],
      [Op.lte]: createTime[1]
    }
  }


  const result = await Ask.findAndCountAll({
    limit: +pageSize,
    offset: pageSize * pageIndex,
    order: [
      [ 'id', 'desc' ]
    ],
    include: [
      {
        model: House,
        attributes: [ 'name' ],
        where: whereUser,
        include: [
          {
            model: User,
            as: 'user',
            attributes: [ 'nickName' ]
          }
        ]
      },
      {
        model: User,
        attributes: [ 'nickName' ]
      }
    ],
    where
  })

  return {
    count: result.count,
    data: result.rows
  }
}

const createAsk = async ({content, rent, startTime, endTime, houseId, askId, reason, status}) => {
  const result = await Ask.create({
    content,
    rent,
    startTime,
    endTime,
    houseId,
    askId,
    reason,
    status
  })

  const data = result.dataValues

  return data
}

const updateAsk = async ({content, rent, startTime, endTime, reason, status, id}) => {
  const whereOpt = {
    id
  }
  const result = await Ask.update({
    content,
    rent,
    startTime,
    endTime,
    reason,
    status
  }, {
    where: whereOpt
  })

  const data = result.length > 0

  return data
}

const delAsk = async (id) => {
  const result = await Ask.destroy({
    where: {
      id
    }
  })

  return result > 0
}

const getAskOne = async (id) => {
  const result = await Ask.findOne({
    where: {
      id
    },
    include: [
      {
        model: House,
        include: [
          {
            model: User,
            as: 'user',
            attributes: [ 'nickName' ]
          },
          {
            model: Area,
            attributes: [ 'name' ]
          }
        ]
      },
      {
        model: User,
        attributes: [ 'nickName' ]
      }
    ]
  })

  return result.dataValues
}

module.exports = {
  getAskList,
  createAsk,
  updateAsk,
  delAsk,
  getAskOne
}
